<template>
  <div class="address" :style="{ minHeight: bodyHeight + 'px' }">
    <overlay v-if="this.showMaskLayer"></overlay>
    <div class="address-list-wrap" v-else>
      <div class="addressContent" v-if="$route.name === 'my-address'">
        <div class="addressList">
          <helper v-if="!originAddresslist.length">
            <svg class="icon" aria-hidden="true" slot="image">
              <use xlink:href="#icon-dizhiweikong"></use>
            </svg>
            <span slot="helperText">{{ $t("addressListEmpty") }}</span>
          </helper>
          <div class="show-list" v-else>
            <van-address-list
              v-model="chosenAddressId"
              :list="addressList"
              @add="onAdd"
              @edit="onEdit"
              @select="onChange"
            ></van-address-list>
          </div>
        </div>
        <div class="newAddress" v-if="!originAddresslist.length">
          <van-button type="danger" @click="onAdd" round>
            {{ $t("addAddress") }}
          </van-button>
        </div>
      </div>
      <router-view
        @updateNew="updateNew"
        @sendNew="sendNew"
        @deleteAdd="deleteAdd"
        :receive="sendToChild"
      ></router-view>
    </div>
  </div>
</template>

<script>
import helper from 'components/content/helper/helper';
import overlay from 'components/content/overlay/overlay.vue';
import { mapMutations, mapState } from 'vuex';
import { AddressList, Button } from 'vant';
import 'vant/lib/address-list/style/less';

export default {
    name: 'address-list',
    components: {
        [Button.name]: Button,
        [AddressList.name]: AddressList,
        helper,
        overlay
    },
    data () {
        return {
            addressList: [],
            chosenAddressId: '',
            sendToChild: {},
            originAddresslist: [],
            fromRouteName: '',
            bodyHeight: 0
        };
    },
    created () {
    // 加载该用户的地址列表信息
        this.resetStatus({ state: 'showMaskLayer', status: true });
        this.$api.addressApi
            .get({ id: localStorage.getItem('id') })
            .then(res => {
                if (res.data && res.data.length) {
                    this.originAddresslist = res.data;
                    this.pickData(res.data);
                }
            })
            .catch(err => {
                this.$util.failToast(this.$t('addressListEmpty'));
                throw err;
            })
            .then(() => {
                this.resetStatus({ state: 'showMaskLayer', status: false });
            });
    },
    mounted () {
        this.bodyHeight = this.$util.ScreenCanUseHeight();
    },
    methods: {
        onAdd () {
            this.$router.push({ name: 'newAddress' });
        },
        onEdit (choose) {
            const getIndex = _.findIndex(this.originAddresslist, item => {
                return item._id === choose.id;
            });
            this.sendToChild = this.originAddresslist[getIndex];
            this.$router.push({ name: 'editAddress' });
        },
        pickData (data) {
            data.forEach(value => {
                const { _id, name, tel, province, city, county, addressDetail } = value;
                this.addressList.push({
                    id: _id,
                    name,
                    tel,
                    address: province + city + county + addressDetail
                });
            });
        },
        sendNew (newData) {
            // 接收子组件传递过来的新地址数据
            if (this.errormsg) this.errormsg = '';
            this.originAddresslist.push(newData);
            this.pickData([newData]);
        },
        deleteAdd (val) {
            _.remove(this.addressList, (item, index) => {
                if (item.id === val) {
                    this.addressList.splice(index, 1);
                    this.originAddresslist.splice(index, 1);
                }
            });
        },
        onChange (item) {
            if (this.fromRouteName === 'issue-order' || this.fromRouteName === 'updateOrder') {
                this.$store.commit('overRideValue', {
                    state: 'tempIssueOrderInfo',
                    value: {
                        orderAddress: item.address,
                        orderPhone: item.tel,
                        orderAuthor: item.name
                    }
                });
                setTimeout(() => {
                    this.$router.back(-1);
                }, 400);
            }
        },
        updateNew (data) {
            this.addressList.forEach((item, index) => {
                if (item.id === data.id) {
                    const { province, city, county, addressDetail, name, tel } = data;
                    this.addressList.splice(index, 1, {
                        id: item.id,
                        name,
                        tel,
                        address: province + city + county + addressDetail
                    });
                    this.updateOriginList(data, index);
                }
            });
        },
        updateOriginList (data, index) {
            this.originAddresslist[index] = Object.assign(data);
        },
        ...mapMutations(['resetStatus'])
    },
    computed: {
        ...mapState(['showMaskLayer'])
    },
    beforeRouteEnter (to, from, next) {
        next(vm => {
            vm.fromRouteName = from.name;
        });
    }
};
</script>

<style scoped lang="less" src="./less/address-list.less"></style>
